#!/bin/bash
#
# Copyright (C) 2017 ~ 2018 Deepin Technology Co., Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

if ! is_sw; then
  return 0
fi

if [ ! -d /media/cdrom/live/platform ]; then
  msg "/media/cdrom/live/platform is not exists!"
  # failed when the directory is not exists
  return 1
fi

SYSTEM_NAME=$(cat /proc/cpuinfo | grep "system type" | awk '{print $4}')
case `uname -r` in
  *-tembin-s41)
    SYSTEM_NAME=${SYSTEM_NAME}-s41
      ;;
  *-tembin-s40)
    SYSTEM_NAME=${SYSTEM_NAME}-s40
      ;;
esac

msg "CPUTYPE=$SYSTEM_NAME"

SRCPATH=/media/cdrom/live/platform/$SYSTEM_NAME
rm -rf /boot/*
rm -rf /lib/modules/*
[ -d /media/cdrom/live/boot ] && cp -rvf /media/cdrom/live/boot/* /boot/

[ -f $SRCPATH/xorg.conf ] && \
  install -v -Dm644 $SRCPATH/xorg.conf /etc/X11/xorg.conf

# Replace kernel image and modules.
mkdir -pv /lib/modules
[ -d $SRCPATH/modules ] && cp -rf $SRCPATH/modules/* /lib/modules

for _FILE in $(ls ${SRCPATH} | grep "^vmlinu"); do
  install -v -Dm755 ${SRCPATH}/${_FILE} /boot/${_FILE}
done

for _KERVER in $(ls /lib/modules); do
  if [ -d /lib/modules/${_KERVER} ]; then
    /usr/sbin/update-initramfs -c -k ${_KERVER} || true
  fi
done

sed -i "/overlayfs/d" /etc/fstab

DI_ROOT_PARTITION=$(cat /deepinhost/etc/deepin-installer.conf | \
  grep "^DI_ROOT_PARTITION=" | awk -F'=' '{print $2}')
LOCALUUID=$(blkid -s UUID -o value ${DI_ROOT_PARTITION})

mkdir -p /boot/grub


msg "LOCALUUID: $LOCALUUID"
if [ -f ${SRCPATH}/grub.cfg ]; then
  KERVER=$(uname -r)
  sed -e "s|root=|root=UUID=$LOCALUUID|g" -e "s|@KERNEL_VERSION@|${KERVER}|g" \
    ${SRCPATH}/grub.cfg > /boot/grub/grub.cfg
elif [ -f ${SRCPATH}/grub.cfg.head ]; then
  cat ${SRCPATH}/grub.cfg.head > /boot/grub/grub.cfg

  for _KERVER in $(ls /lib/modules); do
    if [ -d /lib/modules/${_KERVER} ]; then
	  sed -e "s|root=|root=UUID=$LOCALUUID|g" \
	-e "s|live-media=|live-media=UUID=$LOCALUUID|g" \
        -e "s|@KERNEL_VERSION@|${_KERVER}|g" \
        ${SRCPATH}/grub.cfg.menu >> /boot/grub/grub.cfg
    fi
  done
fi

if cat /deepinhost/etc/deepin-installer.conf | grep DI_MOUNTPOINTS | \
  grep -q -e "=/boot;" -e "=/boot$"; then
    msg "/boot split detected"
   cd /boot 
   ln -sv . boot
fi

if [ x$(installer_get "DI_CRYPT_ROOT") == xtrue ]; then
    sed -i 's/splash//g' /boot/grub/grub.cfg
fi

return 0
